(function(win) {
    /*
    * 加入购物车的提示
    * 1、success() 显示提示
    * 2、fail().   显示失败
    * @param {dom} parentNode 放toast的父节点
    * @param {obj} options    toast显示的时候，可以传入的一些参数
    *
    * toast采用absolute定位，所以父节点需要注意定位方式
    * */
    win.$carToast = {
      _inited: false,
      _parentNode: null,
      _rect: null,
      _options: null,

      success: function(parentNode, options) {
        this.show(parentNode, options, 'success');
      },

      fail:function(parentNode, options) {
        this.show(parentNode, options, 'fail');
      },

      show: function(parentNode, options, type) {
        if(!parentNode || !type) {
          return;
        }
        this.prepareOptoins(options);
        if (this._options.global) {
          // 全局，toast节点放在body中
          this._rect = this.getOffset(parentNode[0]);
          parentNode = $('body');
        }

        if (!this._inited) {
          this._inited = true;
          $('body').append(this.getToastStyle(this.getStyleObj(this._options)));
        }

        this._parentNode = parentNode;
        var toastNode = parentNode.find('.shopcart_toast');
        var toastText = type == 'success' ? '成功加入购物车' : this._options.failText;

        if (toastNode) {
          var timeId = toastNode.data('timeId');
          if (timeId) {
            clearTimeout(timeId);
          }
          toastNode.remove();
          toastNode = null;
        }

        parentNode.append(this.getToastTemplate());
        toastNode = parentNode.find('.shopcart_toast');
        toastNode.addClass('show ' + type);
        toastNode.find('.shopcart_toast_text').text(toastText);
        this.setToastStyleInline(toastNode, this._options, this._rect);
        this.hideToast(toastNode);
      },

      hideToast: function(toastNode) {
        var timeId = setTimeout(function() {
          toastNode.addClass('hide');
          toastNode.data('timeId', '');
          setTimeout((function(node) {
            return function() {
              node.remove();
              node = null;
            }
          })(toastNode), 500);
        }, 2500);
        toastNode.data('timeId', timeId);
      },

      /**
       * options，一些可选的参数设定
       * bottom: 距离底部的距离
       * marginLeft: 往左的margin值
       * failText: 错误的提示文字
       * global: 是否全局的
       */
      getDefaultOptions: function() {
        return {
            bottom: '20px',
            marginLeft: '-73px',
            failText: '系统繁忙请稍后',
            global: false
        };
      },

      /**
       * 传递一些自定义的参数
       * @param {string} bottom [距离底部的距离]
       * @param {string} failText [出错的提示文案]
       */
      prepareOptoins: function(options) {
        this._options = this.getDefaultOptions();
        if (!options && !typeof options !== 'object') {
          return;
        }
        for (var name in options) {
          if (typeof options[name] !== 'undefined') {
            this._options[name] = options[name];
          }
        }
      },

      getScroll: function(target, top) {
        var prop = top ? 'pageYOffset' : 'pageXOffset';
        var method = top ? 'scrollTop' : 'scrollLeft';
        var ret = target[prop];

        if (typeof ret !== 'number') {
          ret = window.document.documentElement[method];
        }
        return ret;
      },
      //获取偏差值
      getOffset: function (element) {
        var rect = element.getBoundingClientRect();
        var scrollTop = this.getScroll(window, true);
        var scrollLeft = this.getScroll(window);
        
        var docEl = window.document.body;
        var clientTop = docEl.clientTop || 0;
        var clientLeft = docEl.clientLeft || 0;

        return {
          top: rect.top + scrollTop - clientTop,
          left: rect.left + scrollLeft - clientLeft,
          width: rect.width
        };
      },

      getToastTemplate: function() {
          return '<div class="shopcart_toast">'+
                      '<i class="shopcart_toast_arrow"></i>'+
                      '<div class="shopcart_toast_info">'+
                          '<i class="shopcart_toast_icon success iconfont">&#xe632;</i>'+
                          '<i class="shopcart_toast_icon fail iconfont">&#xe601;</i>'+
                          '<span class="shopcart_toast_text"></span>'+
                      '</div>'+
                  '</div>';
      },

      /**
       * 设置行内样式，避免同页面中，不同toast的展示传参不同
       */
      setToastStyleInline: function(node, options, rect) {
        if (options.global) {
          // 全局情况下，行内样式设置top,left等值 
          node.css('margin-left', '0');
          node.css('bottom', 'auto');
          node.css('top', (rect.top-30)+'px');
          node.css('left', (rect.left + rect.width/2 - node.width()/2)+'px');
        } else {
          if (options.marginLeft) {
            node.css('margin-left', options.marginLeft);
          }
          if (options.bottom) {
            node.css('bottom', options.bottom);
          }
        }
      },

      getToastStyle: function(styleObj) {
        var result = '';
        if (!styleObj){
            return result;
        }
        result += '<style>'
        for (var name in styleObj) {
          var tempStr = '';
          var styleItem = styleObj[name];
          tempStr += (name + '{');
          for (var n in styleItem) {
            if (typeof styleItem[n] == 'string') {
              if (n == 'animation' || n == 'transform') {
                tempStr += ('-webkit-'+n+':'+styleItem[n]+';');
                tempStr += ('-moz-'+n+':'+styleItem[n]+';');
                tempStr += ('-ms-'+n+':'+styleItem[n]+';');
              }
              tempStr += (n+':'+styleItem[n]+';');
            } else if (typeof styleItem[n] == 'object') {
              tempStr += (n+this.getStyleObjString(styleItem[n]));
            }
          }
          tempStr += '}';
          if (name == '@keyframes toastShow' || name == '@keyframes toastHide') {
            result += ('@-webkit-'+tempStr.slice(1));
            result += ('@-moz-'+tempStr.slice(1));
          }
          result += tempStr;
        }
        return result+'</style>';
      },

      getStyleObjString: function(style) {
        var result = ''
        if (typeof style == 'object') {
          // 把前后花括号带上{}
          for (var name in style) {
            if (name == 'animation' || name == 'transform') {
              result += ('-webkit-'+name + ':' + style[name]+ ';');
              result += ('-moz-'+name+':'+style[name]+';');
              result += ('-ms-'+name+':'+style[name]+';');
            }
            result += (name + ':' + style[name]+ ';')
          }
        }
        return '{'+result+'}';
      },

      getStyleObj:  function(options){
        return {
          '.shopcart_toast': {
            'display': 'none',
            'position': 'absolute',
            'left': '50%',
            'margin-left': options.marginLeft,
            'bottom': options.bottom,
            'text-align': 'center',
            'font-size': '12px',
            'font-weight': 'bold',
            'border': '3px solid rgba(0, 0, 0, 0.2)',
            'color': '#333',
            'z-index': '1001'
          },
          '.shopcart_toast.show': {
            'display': 'block',
            'animation': 'toastShow .5s  ease both',
          },
          '@keyframes toastShow': {
            '0%': {
              'opacity': '0',
              'transform': 'translateY(0)',
            },
            '100%': {
              'opacity': '1',
              'transform': 'translateY(-10px)',
            }
          },
          '.shopcart_toast.hide': {
            'display': 'block',
            'opacity': '1',
            'animation':'toastHide .5s  ease both',
          },
          '@keyframes toastHide': {
            '0%': {
              'opacity': '1',
              'transform': 'translateY(-10px)',
            },
            '100%': {
              'opacity': '0',
              'transform': 'translateY(0)',
            }
          },
          '.shopcart_toast .shopcart_toast_info': {
            'width': '138px',
            'height': '32px',
            'line-height': '32px',
            'background-color': '#fff',
            'border': '1px solid #b4b4b4',
            'white-space': 'nowrap',
            'text-indent': '0'
          },
          '.shopcart_toast .shopcart_toast_arrow': {
            'position': 'absolute',
            'width': '0',
            'height': '0',
            'bottom': '-6px',
            'left': '67px',
            'border-style': 'solid',
            'border-width': '7px 7px 0 7px',
            'border-color': '#b4b4b4 transparent transparent transparent'
          },
          '.shopcart_toast .shopcart_toast_arrow:after': {
            'content': '""',
            'position': 'absolute',
            'top': '-7px',
            'left': '-6px',
            'width': '0',
            'height': '0',
            'border-left': '6px solid transparent',
            'border-top': '6px solid #fff',
            'border-right': '6px solid transparent'
          },
          '.shopcart_toast .shopcart_toast_icon,.shopcart_toast .shopcart_toast_text': {
            'display': 'inline-block',
            'vertical-align': 'middle',
            'line-height': '32px'
          },
          '.shopcart_toast .shopcart_toast_icon': {
            'display': 'none',
            'font-family': 'iconSearch',
            'font-style': 'normal',
            'font-size': '14px',
            'margin-right': '6px'
          },
          '.shopcart_toast .shopcart_toast_icon.success': {
            'color': '#75ac2b'
          },
          '.shopcart_toast .shopcart_toast_icon.fail': {
            'color': '#ff895d'
          },
          '.shopcart_toast.success .shopcart_toast_icon.success,.shopcart_toast.fail .shopcart_toast_icon.fail' :{
            'display': 'inline-block'
          }
        };
      }
    };
})(window);
